package first.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


@WebServlet(name = "MyServlet4",value = "/servlet4")
public class MyServlet4 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //接受用户发送的数据
        //request, 请求对象：封装了浏览器发送的所有数据，请求报文
        //response，响应对象:封装服务器发送给浏览器的数据，响应报文
        //修改编码
        request.setCharacterEncoding("utf-8");  // utf8  my.ini  对post请求起作用
        //response.setCharacterEncoding("utf-8");// 设置响应编码,缺点。导致浏览器会用错编码
        response.setContentType("text/html;charset=utf-8"); // 设置响应内容类型及编码，在响应报文中添加一个响应头content-type:text/html;charset=utf-8

        String username = request.getParameter("username");
        String age = request.getParameter("age");
        System.out.println(username+" "+age);

        //响应内容
        //getWrite()和getOutputStream()只能用一个，不能同时用
        PrintWriter out = response.getWriter();
        // ServletOutputStream out2 = response.getOutputStream();
        out.println("<h1>接受成功!</h1>");

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
